package cn.hpclub.server.model;

import java.io.Serializable;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;

public class Notice extends Model<Notice> implements Serializable{

    private static final long  serialVersionUID = -99855379613217315L;

    public static final Notice dao              = new Notice();

    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = " from notice n where n.is_deleted = 0 ";

        sqlExceptSelect += " and n.org_id in("
                + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true) + ") ";

        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " order by n.sort asc ";

        return sqlExceptSelect;
    }

    private String buildQuery(Entry<String, String> item){
        String sql = "";
        if(item.getKey().equals("type")){
            sql += " and n.type = " + item.getValue() + " ";
        } else if(item.getKey().equals("enabled") && !"-1".equals(item.getValue())){
            sql += " and n.enabled = " + item.getValue() + " ";
        } else if(item.getKey().equals("startTime")){
            sql += " and n.created_time >= '" + item.getValue() + " 00:00:00" + "' ";
        } else if(item.getKey().equals("endTime")){
            sql += " and n.created_time <= '" + item.getValue() + " 23:59:59" + "' ";
        } else if(item.getKey().equals("title")){
            sql += " and title like '%" + item.getValue() + "%' ";;
        }
        return sql;
    }

    public String getNoticeListSqlForClient(int orgId){
        return "select id, title from notice where is_deleted=0 and enabled =1 and org_id in "
                + InterfaceUtil.getParentOrgIdSql(orgId, 3) + " ORDER BY sort asc";
    }

    public Page<Record> getNoticeList(int pageNumber, int pageSize, String keyword, int orgId){
        String sqlExceptSelect = " from notice where is_deleted = 0 and enabled=1";
        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }
        if(StrKit.notBlank(keyword)){
            sqlExceptSelect += " and title like '%" + keyword + "%'";
        }

        sqlExceptSelect += " ORDER BY sort asc";
        // System.out.println("sql = select * " + sqlExceptSelect);
        return Db.paginate(pageNumber, pageSize, "select *", sqlExceptSelect);
    }
}
